package com.cdinternationalcompany.syhapp.utils

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Looper
import android.content.ContentResolver
import android.provider.Settings
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import com.cdinternationalcompany.syhapp.App
import com.cdinternationalcompany.syhapp.push.Constants
import com.cdinternationalcompany.syhapp.push.ManufacturerHelper
import com.cdinternationalcompany.syhapp.push.TokenObserver
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

interface OnFlutterCall {
    companion object {
        const val CHANNEL_RESULT_OK = "OK"
    }

    fun call(arguments: String, result: MethodChannel.Result): Any
}

class ChannelManager {
    private lateinit var mMethodChannel: MethodChannel
    private lateinit var mEventChannel: EventChannel
//    private val mHandler = android.os.Handler()
    var mEventSink: EventChannel.EventSink? = null

    private val mMap: HashMap<String, OnFlutterCall> = HashMap()

    companion object {
        private val TAG = ChannelManager::class.java.simpleName
        val instance by lazy(LazyThreadSafetyMode.NONE) {
            ChannelManager()
        }

    }

    fun initChannel(
        messenger: BinaryMessenger?,
        context: Context,
        contentResolver: ContentResolver
    ) {
//        mMethodChannel = MethodChannel(messenger!, "com.app.framework.channel/api")
        if (messenger != null) {
            mMethodChannel = MethodChannel(messenger, "com.app.framework.channel/api")
        };
        mEventChannel = EventChannel(messenger, "PushApi/registerId");
        mEventChannel.setStreamHandler(object : EventChannel.StreamHandler {
            override fun onCancel(arguments: Any?) {

                Log.d(TAG, "EventChannel onCancel called")
            }

            override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                mEventSink = events
//                mHandler.postDelayed({
//                    TokenObserver.instance.collectionToken(context)
//
//                }, 4000)
                Log.d(TAG, "EventChannel onListen called")
            }
        }
        )
        mMethodChannel.setMethodCallHandler { call, result ->
            var arguments = ""
            if (call.arguments != null) {
                arguments = call.arguments as String

            }
            if (call.method != null) {

                if (call.method.equals("NavigationAPI/openAR")) {

                } else if (call.method.equals("NavigationAPI/openTransform")) {
//                    val alipay = PayTask(this)
                } else if (call.method.equals("NavigationAPI/getAndroidId")) {
                    var id = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID);
                    val numbersMap = mutableMapOf("androidId" to id, "platform" to "platform")
                    result.success(numbersMap);
                    callFlutter("PushApi/registerId", numbersMap)
                } else if (call.method.equals("NavigationAPI/getRegistrationID")) {
//                    App().initPushSdk()NavigationAPI/initNative
                } else if (call.method.equals("NavigationAPI/apkVerifyWithSHA")) {

//                    MainActivity().initpackageManager();
                } else if (call.method.equals("NavigationAPI/initNative")) {
                    try {

//                        (context as? Activity)?.runOnUiThread {
//                        App().initPushSdk()
                        try {
                            val application = context.applicationContext as Application
                            (application as? App)?.initPushSdk()
                        } catch (e: Exception) {
                            Log.w(Constants.tag, e)
                        }
//                        Application()


//                        }
                    } catch (e: Exception) {
                        Log.w(Constants.tag, e)
                    }
//                    SingatureClass.apkVerifyWithSHA(context,"fd1fcd690e14f33e83008895c8ffb24d");
//                    MainActivity().initpackageManager();
                }
//                else if (call.method.equals("NavigationAPI/getTokenAPI")) {
//                    Thread {
//                        run {
//                            val id = HmsInstanceId.getInstance(context).getToken("104514229", "HCM")
//                            if (!TextUtils.isEmpty(id)) {
//                                val para = mapOf<String,String>(Pair("token",id),Pair("platform","2"))
//
//                                android.os.Handler(Looper.getMainLooper()).post{
//                                    callFlutter("token",para)
//                                }
//                                HmsMessaging.getInstance(context).turnOnPush()
//                            }
//                        }
//                    }.start()
//                }
            }

            Log.d(TAG, "Flutter call Native method -> ${call.method}], args -> ${call.arguments}")
            mMap[call.method]?.call(arguments, result)
        }
    }

    fun on(method: String, caller: OnFlutterCall) {
        mMap[method] = caller
    }

    fun callFlutter(method: String, arguments: Any) {
        android.os.Handler(Looper.getMainLooper()).post {
            mEventSink?.success(arguments)
        }

    }

}